﻿using B.S.DataBase.MyProject.Domain.BOM;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using System.Security.Cryptography;
using T.E.ERP.Read.API.Applicantions.Command.BomCOmmand;
using T.E.ERP.Read.API.Dtos.Dtos;

namespace T.E.ERP.Read.API.Applicantions.CommandHandler.BomConnamdHandler
{
    /// <summary>
    /// 反填Bom信息命令处理
    /// </summary>
    public class ReverseBomCommandHandler : IRequestHandler<ReverseBomCommand, APIResult<List<BomDTO>>>
    {
        private readonly IBaseRepository<BomInfo> bomRep;
        private readonly IBaseRepository<BomParts> bompartRep;
        public ReverseBomCommandHandler(IBaseRepository<BomInfo> bomRep, IBaseRepository<BomParts> bompartRep)
        {
            this.bomRep = bomRep;
            this.bompartRep = bompartRep;
        }

        public async Task<APIResult<List<BomDTO>>> Handle(ReverseBomCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<BomDTO>> result = new APIResult<List<BomDTO>>();

            var bomInfos = await bomRep.GetAll();
            var bomParts = await bompartRep.GetAll();

            var list = from a in bomInfos
                       where a.BomCode == request.BomCode
                       select new BomDTO
                       {
                           BId = a.BId,
                           BomCode = a.BomCode,
                           DefaultBom = a.DefaultBom,
                           ProductType = a.ProductType,
                           ProductName = a.ProductName,
                           Remarks = a.Remarks,
                           ProductionNum = a.ProductionNum,
                           BomTheme = a.BomTheme,
                           BomVersion = a.BomVersion,
                           EstimatedCost = a.EstimatedCost,
                           Inventory = a.Inventory,
                           BomParts = bomParts
                              .Where(b => b.BomCode == a.BomCode)
                              .ToList()
                       };

            result.Code = APIEnum.成功;
            result.Msg = APIEnum.查询成功.ToString();
            result.data = list.ToList();
            return result;
        }
    }
}